package com.a3g.findnumber;

import java.util.ArrayList;

import android.app.Activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.a3g.findnumber.entity.CustomGridViewAdapter;
import com.a3g.findnumber.entity.Item;
import com.a3g.findnumber.entity.MusicService;
import com.a3g.findnumber.entity.Star;
import com.a3g.findnumber.entity.ThreadTime;

public class GamePlayAct extends Activity implements OnClickListener {

	private static int INCREASE_SCORE = 10;

	private ArrayList<Star> listStars;

	private ImageView theMoon;

	private int selectedStarCode;

	private int score;

	private int level;

	MediaPlayer mClickStar;
	
	GridView playGridView;

	ArrayList<Item> numberArray = new ArrayList<Item>();

	CustomGridViewAdapter numberGridAdapter;

	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_play);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		// Stop background music
		if (StartAct.isMusicMute == true) {
			stopService(new Intent(this, MusicService.class));
		}

		Intent intent = getIntent();
		this.selectedStarCode = intent.getIntExtra("Color", 3);
		this.score = intent.getIntExtra("Score", 0);
		this.level = intent.getIntExtra("Level", 1);

		//this.initial();

		// Set score
		//TextView scoreLabel = (TextView) findViewById(R.id.currentScore);
		//scoreLabel.setText("SCORE: " + this.score);
		
		playGridView = (GridView) findViewById(R.id.playGridView);
		
		int numColumns = 7;
		playGridView.setNumColumns(numColumns);
		
		final String[] numbers = inputData(7, 7, 2, 9);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, numbers);
		
		playGridView.setAdapter(adapter);
		
//		// set grid view item
//				Bitmap homeIcon = BitmapFactory.decodeResource(this.getResources(),R.drawable.one_number);
//				int maxRow = 49;
//				
//				for (int i = 0; i < maxRow; i++) {
//					numberArray.add(new Item(homeIcon,"level_01_button"));
//				}
//				
//				playGridView = (GridView) findViewById(R.id.playGridView);
//				numberGridAdapter = new CustomGridViewAdapter(this, R.layout.row_grid, numberArray);
//				int numColumns = 7;
//				playGridView.setNumColumns(numColumns);
//				playGridView.setAdapter(numberGridAdapter);

		//ThreadTime.createNewThreadTime(this, this.level);

//		this.theMoon = (ImageView) findViewById(R.id.moonFull);
		//TranslateAnimation animation = this.getCoundownAnimation(this.theMoon,	ThreadTime.getLevelDuration(this.level));
		//this.theMoon.startAnimation(animation);

	}

	private TranslateAnimation getCoundownAnimation(ImageView moonBlack, int time) {

//		TranslateAnimation animation = new TranslateAnimation(moonBlack.getX(),
//				moonBlack.getX() + 120, moonBlack.getY(), moonBlack.getY());

		TranslateAnimation animation = new TranslateAnimation(moonBlack.getX(),
		moonBlack.getX() + 120, moonBlack.getY(), moonBlack.getY());
		
		animation.setDuration(time + 200);
		// animation.setRepeatCount(5);
		animation.setRepeatMode(0);
		animation.setFillAfter(true);

		return animation;
	}

	private void initial() {

		RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		//RelativeLayout paneLayout = (RelativeLayout) findViewById(R.id.playPanel);

		this.listStars = this.createStars();

		int id = 0;
		for (Star star : listStars) {

			rel_btn = new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

			star.setBackgroundResource(star.getStarImage());

			// ADD by duongza
			int n = getRandomNumber();
			if (n >= 5) {
				// Step1 : create the RotateAnimation object
				RotateAnimation anim = new RotateAnimation(0f, 360f, 15f, 15f);
				// Step 2: Set the Animation properties
				anim.setInterpolator(new LinearInterpolator());
				anim.setRepeatCount(Animation.INFINITE);
				anim.setDuration(900);

				// Step 3: Start animating the image
				star.startAnimation(anim);
				// END

			} else {
				// Step1 : create the RotateAnimation object
				ScaleAnimation anim = new ScaleAnimation(1f, 0.1f, 1f, 0.1f);
				// Step 2: Set the Animation properties
				anim.setInterpolator(new LinearInterpolator());
				anim.setRepeatCount(Animation.INFINITE);
				anim.setDuration(900);

				// Step 3: Start animating the image
				star.startAnimation(anim);
				// END
			}

			// END

			star.setId(id);
			id++;

			rel_btn.leftMargin = star.getStarX();
			rel_btn.topMargin = star.getStarY();

			star.setLayoutParams(rel_btn);
			//paneLayout.addView(star);

			star.setOnClickListener(this);
		}
	}

	public ArrayList<Star> createStars() {

		// ---------- Get Display Size ----------//
		DisplayMetrics dimension = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dimension);

		int screenWidth = dimension.widthPixels;
		int screenHeight = dimension.heightPixels;

		if (listStars == null || listStars.size() <= 0) {

			this.listStars = new ArrayList<Star>();

			// --------- Create Star here ----------//
			Star redStar = new Star(this);
			redStar.initialStar(R.drawable.bg_star_red, screenWidth,
					screenHeight, listStars);
			listStars.add(redStar);

			Star greenStar = new Star(this);
			greenStar.initialStar(R.drawable.bg_star_green, screenWidth,
					screenHeight, listStars);
			listStars.add(greenStar);

			Star violetStar = new Star(this);
			violetStar.initialStar(R.drawable.bg_star_violet, screenWidth,
					screenHeight, listStars);
			listStars.add(violetStar);

			Star yellowStar = new Star(this);
			yellowStar.initialStar(R.drawable.bg_star_yellow, screenWidth,
					screenHeight, listStars);
			listStars.add(yellowStar);

			Star blueStar = new Star(this);
			blueStar.initialStar(R.drawable.bg_star_blue, screenWidth,
					screenHeight, listStars);
			listStars.add(blueStar);

		} else {
			for (Star star : listStars) {
				star.resetLocation();
			}

			for (Star star : listStars) {
				star.autoGenerateLocation(screenWidth, screenHeight,
						this.listStars);
			}
		}

		return listStars;
	}

	@Override
	public void onClick(View view) {
		int resId;
		Button choiceButton = (Button) view;
		int buttonId = choiceButton.getId();
		int choiceStarCode = this.listStars.get(buttonId).getStarImage();

		if (choiceStarCode == selectedStarCode) {
			resId = R.raw.true_click_music;
		} else {
			resId = R.raw.false_click_music;
		}

		// Release any resources from previous MediaPlayer
		if (mClickStar != null) {
			mClickStar.release();
		}

		// Create a new MediaPlayer to play this sound
		if (StartAct.isSpeakerMute == false) {
			mClickStar = MediaPlayer.create(this, resId);
			mClickStar.start();
		}

		if (choiceStarCode == selectedStarCode) {
			this.score += this.calculateScore();
			this.reload();

		} else {
			this.finishGame(this.score, 100);
		}

	}

	public void setTime(int countDown) {
		// ---- Set Progress Bar ----------//
		Log.e("ThreadTime", "Time: " + countDown);
		if (countDown > 0) {

		} else {
			// this.score += this.calculateScore();
			this.score = this.score + this.calculateScore() - INCREASE_SCORE;
			this.finishGame(this.score, 100);
		}
	}

	private void reload() {

		if (this.score <= 40) {
			this.level = 1;
		} else if (this.score <= 100) {
			this.level = 2;
		} else if (this.score <= 150) {
			this.level = 3;
		} else if (this.score <= 200) {
			this.level = 4;
		} else {
			this.level = 5;
		}

		Intent playIntent = getIntent();
		playIntent.putExtra("Score", this.score);
		playIntent.putExtra("Level", this.level);
		// playIntent.putExtra("IsPlaying", this.isPlaying);
		finish();

		startActivity(playIntent);

	}

	private void finishGame(int score, int timePlay) {

		finish();

		ThreadTime.destroyThreadTime();

		Intent finishIntent = new Intent(getApplicationContext(),
				FinishAct.class);
		finishIntent.putExtra("Score", score);
		finishIntent.putExtra("TimePlay", timePlay);

		startActivity(finishIntent);
	}

	private int calculateScore() {
		int result = 0;
		result = this.level * GamePlayAct.INCREASE_SCORE;
		return result;
	}

	@Override
	protected void onDestroy() {
		if (null != mClickStar) {
			mClickStar.release();
		}

		super.onDestroy();

	}

	private int getRandomNumber() {
		int number = (int) (Math.random() * 10);
		return number;

	}

	@Override
	public void onPause() {
		if (StartAct.isApplicationSentToBackground(this)) {
			// Stop music when Home Key being Pressed
			stopService(new Intent(this, MusicService.class));
		}
		super.onPause();
	}
	
	private String[] inputData(int maxRow, int maxColumn, int iSelected, int limitColor) {

		int r = 0;
		int length = maxRow * maxColumn;
		String matrix[] = new String[length];
		String st = "0";
		// i row and j column
		int i1 = (int) (Math.random() * length);

		// Input data
		for (int i = 0; i < length; i++) {

			r = (int) (Math.random() * limitColor);
			while (r == 0 || r == iSelected) {
				r = (int) (Math.random() * limitColor);
			}
			st = Integer.valueOf(r).toString();
			matrix[i] = st;
			Log.e("matrix[i]", matrix[i]);
		}

		matrix[i1] = Integer.valueOf(iSelected).toString();

		return matrix;

	}

}